package com.csu.Controller;

import com.csu.model.Account;
import com.csu.service.AccountService;
import jakarta.validation.Valid;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@Valid
@SessionAttributes(value = {"loginAccount"})
public class AccountController {
    @Autowired
    AccountService accountService;
    @GetMapping("/loginForm")
    public String loginForm(){          //登录页面
        return "account/loginForm";
    }

    @PostMapping("/login")
    public String login(@Validated Account account1, BindingResult bindingResult, Model model){         //登录
        StringBuilder sb = new StringBuilder();
        if (bindingResult.hasErrors()){         //验证
            for(ObjectError error : bindingResult.getAllErrors()){
                sb.append(error.getDefaultMessage());
                sb.append(",");
            }
            model.addAttribute("loginMsg" ,sb.substring(0,sb.length()-1));
            return "account/loginForm";
        }

        Account account = accountService.getAccount(account1.getUsername(), account1.getPassword());
        model.addAttribute("loginAccount", account);            //值名与注解相同
        return "catalog/main";
    }


}
